import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'music_list_page.dart';
import 'search_page.dart';
import 'my_page.dart';
import '../services/audio_service.dart';

class MainTabPage extends StatefulWidget {
  @override
  _MainTabPageState createState() => _MainTabPageState();
}

class _MainTabPageState extends State<MainTabPage> with WidgetsBindingObserver {
  int _currentIndex = 1; // 默认选中列表页面
  bool _isDisposed = false;
  // 页面列表
  late List<Widget> _pages;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _pages = [
      SearchPage(),
      MusicListPage(),
      MyPage(),
    ];
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _isDisposed = true;
    // _audioService.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 应用进入后台时暂停播放
    if (state == AppLifecycleState.paused) {
      // _audioService.pause();
    }
  }

  @override
  Widget build(BuildContext context) {
    final audioService = Provider.of<AudioService>(context, listen: true);
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: _pages[_currentIndex],
          ),
          // 添加全局播放控制栏
          if (audioService.currentMusic != null) _buildControlBar(),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) => setState(() => _currentIndex = index),
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.search), label: '搜索'),
          BottomNavigationBarItem(icon: Icon(Icons.list), label: '列表'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
        ],
        showSelectedLabels: true,
        showUnselectedLabels: true,
        type: BottomNavigationBarType.fixed,
      ),
    );
  }


  // 播放控制栏
  Widget _buildControlBar() {
    final audioService = Provider.of<AudioService>(context, listen: true);
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor,
        boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 5)],
      ),
      child: Column(
        children: [
          // 当前播放信息
          Padding(
            padding: const EdgeInsets.only(bottom: 12),
            child: Text(
              '${audioService.currentMusic?.title} - ${audioService.currentMusic?.artist}',
              style: TextStyle(color: Colors.white, fontSize: 16),
              overflow: TextOverflow.ellipsis,
            ),
          ),
          // 进度条
          StreamBuilder<Duration>(
            stream: audioService.positionStream,
            builder: (context, positionSnapshot) {
              return StreamBuilder<Duration?>(
                stream: audioService.durationStream,
                builder: (context, durationSnapshot) {
                  final position = positionSnapshot.data ?? Duration.zero;
                  final duration = durationSnapshot.data ?? Duration.zero;
                  return Column(
                    children: [
                      Slider(
                        value: position.inMilliseconds.toDouble(),
                        max: duration.inMilliseconds.toDouble(),
                        onChanged: (value) => audioService.seek(
                          Duration(milliseconds: value.toInt()),
                        ),
                        activeColor: Colors.white,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            _formatDuration(position),
                            style: TextStyle(
                              color: Colors.white70,
                              fontSize: 12,
                            ),
                          ),
                          Text(
                            _formatDuration(duration),
                            style: TextStyle(
                              color: Colors.white70,
                              fontSize: 12,
                            ),
                          ),
                        ],
                      ),
                    ],
                  );
                },
              );
            },
          ),
          // 控制按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              // 添加播放模式切换按钮
              IconButton(
                icon: _getPlayModeIcon(),
                color: Colors.white,
                onPressed: () => audioService.togglePlayMode(),
              ),
              IconButton(
                icon: Icon(Icons.skip_previous, color: Colors.white, size: 32),
                onPressed: () => audioService.playPrevious(),
              ),
              _buildPlayPauseButton(),
              IconButton(
                icon: Icon(Icons.skip_next, color: Colors.white, size: 32),
                onPressed: () => audioService.playNext(),
              ),
              // 可以保留或移除其他按钮
              IconButton(
                icon: Icon(Icons.volume_up, color: Colors.white),
                onPressed: () => _showVolumeDialog(),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 根据当前模式返回对应的图标
  Widget _getPlayModeIcon() {
    final currentMode = context.watch<AudioService>().currentPlayMode;
    switch (currentMode) {
      case PlayMode.sequence:
        return Icon(Icons.repeat, color: Colors.white);
      case PlayMode.shuffle:
        return Icon(Icons.shuffle, color: Colors.white);
      case PlayMode.repeatOne:
        return Icon(Icons.repeat_one, color: Colors.white);
      default:
        return Icon(Icons.repeat, color: Colors.white);
    }
  }

  // 播放/暂停按钮
  Widget _buildPlayPauseButton() {
    final audioService = Provider.of<AudioService>(context, listen: true);
    return IconButton(
      icon: Icon(
        audioService.currentState.playing
            ? Icons.pause_circle_filled
            : Icons.play_circle_filled,
        color: Colors.white,
        size: 48,
      ),
      onPressed: () => audioService.togglePlayPause(),
    );
  }

  // 显示音量调节对话框
  void _showVolumeDialog() {
    final audioService = Provider.of<AudioService>(context, listen: true);
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('调节音量'),
        content: StreamBuilder<double>(
          // 假设AudioService提供音量流
          stream: audioService.volumeStream,
          builder: (context, snapshot) {
            final currentVolume = snapshot.data ?? 1.0;
            return Slider(
              value: currentVolume,
              min: 0.0,
              max: 1.0,
              divisions: 10,
              label: (currentVolume * 100).toStringAsFixed(0) + '%',
              onChanged: (value) => audioService.setVolume(value),
            );
          },
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  // 格式化时长显示
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return '${duration.inHours > 0 ? '${twoDigits(duration.inHours)}:' : ''}$minutes:$seconds';
  }


}